package com.eu.ebpm.engine.cmd;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.engine.deploy.XmlDefine;
import com.eu.ebpm.engine.entity.args.Param;
import com.eu.ebpm.engine.entity.deploy.Deploy;
import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.deploy.Position;
import com.eu.ebpm.engine.entity.deploy.Transfer;
import com.eu.ebpm.engine.repository.DeployRepository;
import com.eu.ebpm.engine.repository.MissionRepository;
import com.eu.ebpm.engine.repository.TransferRepository;

/**
 * @author wxh
 */
@Component
public class SaveDeployInfoCommand {

	@Autowired
	private DeployRepository deployRepository;
	
	@Autowired
	private MissionRepository missionRepository;
	
	@Autowired
	private TransferRepository transferRepository;
	
	public void execute(XmlDefine define) {
		
		List<Deploy> identicalDeployList = deployRepository.list(Param.map("key", define.getRootDeploy().getKey()));
		for(Deploy identicalDeploy : identicalDeployList) {
			updateIdenticalDeployVersion(identicalDeploy.getId());
		}
		
		for(Deploy deploy : define.getDeploys())  {
			deploy.setActive(true);
			deployRepository.insert(deploy);
		}
		
		for(Mission mission : define.getMissions()) {
			missionRepository.insert(mission);
		}
		
		for(Transfer transfer : define.getTransfers()) {
			transferRepository.insert(transfer);
		}
		
		for(Position position : define.getPositions()) {
			missionRepository.insertPosition(position);
		}
		
	}

	/**
	 * 更新相同key值的流程、以及它们的子流程版本信息
	 */
	private void updateIdenticalDeployVersion(long id) {
		deployRepository.updateVersion(id);
		List<Deploy> subDeployList = deployRepository.list(Param.map("parentId", id));
		for(Deploy subDeploy : subDeployList) {
				updateIdenticalDeployVersion(subDeploy.getId());
		}
	}
	
	
	
	
	
	
	
	

}
